#include <iostream>
#include "Common.hpp"
#include "InetAddr.hpp"
#include "log.hpp"
#include <functional>

using namespace LogModule;

using func_t = std::function<std::string(std::string &)>;

const int default_ln = 5;

class Server
{

public:
    Server(int port, func_t func)
        : _port(port),
          _isrunning(false),
          _func(func)

    {
    }

    void Init()
    {
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::ERROR) << "socket error";
            exit(ExitCode::SOCkET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success!";

        InetAddr addr(_port);
        int n = bind(_listensockfd, addr.GetAddr(), addr.SockLen());
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "bind error";
            exit(ExitCode::BIND_ERR);
        }

        LOG(LogLevel::INFO) << "bind success!";
        n = listen(_listensockfd, default_ln);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "listen error";
            exit(ExitCode::LISTEN_ERR);
        }
        LOG(LogLevel::INFO) << "listen success!";
    }

    void Start()
    {
        _isrunning = true;
        char buffer[1024];
        while (_isrunning)
        {
            sockaddr_in addr;
            unsigned int len = sizeof(addr);
            int sockfd = accept(_listensockfd, COW(addr), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::WARNING) << "accept error";
                continue;
            }
            LOG(LogLevel::INFO) << "accept success";
            InetAddr peer(addr);

            while (1)
            {
                ssize_t n = read(sockfd, buffer, sizeof(buffer));
                if (n < 0)
                {
                    LOG(LogLevel::ERROR) << "read error";
                    close(sockfd);
                    break;
                }
                else if (n == 0)
                {

                    LOG(LogLevel::INFO) << "clients quit";
                    close(sockfd);
                    break;
                }
                else
                {
                    buffer[n] = 0;
                    std::string ret = "client say:";
                    ret += buffer;
                    LOG(LogLevel::INFO) << peer.StringAddr() << ",Client say:" << buffer;
                    ssize_t n = write(sockfd, ret.c_str(), ret.size());
                }
            }
        }

        // close(_listensockfd);
    }

private:
    int _listensockfd;
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};
